package com.project.demo.controller;

import com.project.demo.controller.base.BaseController;
import com.project.demo.entity.BookingRecords;
import com.project.demo.service.BookingRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 预订记录：(BookingRecords)表控制层
 */
@RestController
@RequestMapping("/booking_records")
public class BookingRecordsController extends BaseController<BookingRecords, BookingRecordsService> {

    /**
     * 预订记录对象
     */
    @Autowired
    public BookingRecordsController(BookingRecordsService service) {
        setService(service);
    }


    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = service.readBody(request.getReader());
        this.addMap(paramMap);
        String sql = "SELECT MAX(booking_records_id) AS max FROM " + "booking_records";
        Integer max = service.selectBaseCount(sql);
        sql = ("SELECT count(*) count FROM `tourist_routes` INNER JOIN `booking_records` ON tourist_routes.route_number=booking_records.route_number WHERE tourist_routes.number_of_group_members < " +
                "booking_records.number_of_bookings AND booking_records.booking_records_id=" + max).replaceAll("&#60;", "<");
        Integer count = service.selectBaseCount(sql);
        if (count > 0) {
            sql = "delete from " + "booking_records" + " WHERE " + "booking_records_id" + " =" + max;
            service.deleteBaseSql(sql);
            return error(30000, "名额不足");
        }
        sql = "UPDATE `tourist_routes` INNER JOIN `booking_records` ON tourist_routes.route_number=booking_records.route_number SET tourist_routes.number_of_group_members= tourist_routes" +
                ".number_of_group_members - booking_records.number_of_bookings WHERE booking_records.booking_records_id=" + max;
        service.updateBaseSql(sql);
        return success(1);
    }


}
